const copy = require("./pub/deepcopy");
const createOption = require("./pub/createOption");
const tools = require("./pub/tools");
let _data = {};

class Conf{
    constructor(){
        this._data = _data;
    }

    get( key ){
        let args = Array.prototype.slice.call(arguments);
        if(_data[key] && _data[key].get){
            return _data[key].get.apply( _data[key] , Array.prototype.slice.call(args ,1) );
        }else
            return _data[key];
    }

    set(key , v ){
        console.log( "annt modify conf.   " + key );
        return this;
    }

    do( key , meth ){ 
        let args = Array.prototype.slice.call(arguments);
        if(_data[key] && _data[key][meth] && tools.isType(_data[key][meth] , "Function") ){
            return _data[key][meth].apply( _data[key] , Array.prototype.slice.call(args ,2) );
        }else if( _data[key] && _data[key][meth] && meth.slice(0,1) != "_" ){
            return _data[key][meth];
        }
        return undefined;
    }

    //用于更新来自服务器的配置数据
    upgrade( key , data){
        let isObj = tools.isType(data , "Object");
        let d={};
        if( _data[key] && _data[key].upgrade){
            if(tools.isType(data , "Object")){
                d = Object.assign({},data);
                !tools.isType(d.active,"Undefined") && delete(d.active);
            }else if(tools.isType(data , "Array")){
                d = Object.assign([],data);
            }else{
                d = data;
            }

            _data[key].upgrade(d)
            
        }else if(!isObj && _data[key]){
            _data[key] = data;
        }
    }

    addOption( key , obj ){
        if( !_data[key] )
            _data[key] = createOption( copy( obj ) );
        return this;
    }

    addOptions( obj ){
        obj = obj || {};
        for(let key in obj){
            if( !_data[key] )
                _data[key] = createOption( copy(obj[key]) );
        }
        return this;
    }
}

module.exports = Conf; 